<?php
session_start();

$DocRoot = $_SERVER['DOCUMENT_ROOT'];
include_once "$DocRoot/woflow/conf/pages.inc.php";
include_once "$DocRoot/woflow/conf/sys.inc.php";

// determines the controller for a given controller name
function controllerAt($controllerName) 
{	
	global $DocRoot;
	$file = "$DocRoot/woflow/controller/$controllerName"."_cnt.php";
	if (file_exists($file)) 
	{
		return $file;
	}
	return "$DocRoot/woflow/controller/".SysConf::error_controller."_cnt.php";
}

// parse the request items
function parseRequest($oRequest) 
{
	return array(
		"controller" => $oRequest['c'],
		"method"	 => $oRequest['m'],
		"args" 		 => (isset($oRequest['args']) ? $oRequest['args'] : "")
	);
}

// TODO: use a CSRF token
function isAuthenticated() 
{
	$user = isset($_SESSION['id']) ? $_SESSION['id'] : "";
	$digest = isset($_SESSION['sess']) ? $_SESSION['sess'] : "";
	return ($user != "") && ($digest != "") && (md5($user + md5($user + SysConf::session_secret)) == $digest);
}


function isAuthRequired($controller)
{
	return false; // ($controller != SysConf::unauth_controller);
}

// Test if authenticated
$isAuth = isAuthenticated();

// Primary dispatcher
$oRequest = isset($_GET['c']) ? $_GET : $_POST;
if (isset($oRequest['c']) && isset($oRequest['m']) ) 
{
	// Parse the request
	$aRequest = parseRequest($oRequest);

	// Check if authentication is not required, or if it is then
	// we are authenticated
	if (!isAuthRequired($aRequest['controller']) || $isAuth)
	{
		// Load the controller	
		$sCntlFile =  controllerAt($aRequest['controller']);
		include_once $sCntlFile;

		try {
			// Construct the factory object and get the controller from it
			$oFactory = new ControllerFactory();
			$oController = $oFactory->getController();

			
			// Call the requested method from the controller 
			call_user_func_array(
							array($oController, $aRequest['method']),
							array($aRequest['args'])
					);

		} catch (Exception $e) {
			header("HTTP/1.1 501 Bad Request\r\n");
		}
	}
	else // authentication is required and we're not authenticated
	{
		$sCntFile = controllerAt(SysConf::unauth_controller);
		include_once $cntFile;
		$oFactory = new ControllerFactory();
		$oController = $oFactory->getController();
		session_destroy();
		$oController->page(PagesConf::login_page);
	}
} 
else 
{
	$sCntFile = controllerAt(SysConf::error_controller);
	include_once $cntFile;
	$oFactory = new ControllerFactory();
	$oController = $oFactory->getController();
	$oController->error(404);
}

?>
